<template>
  <view class="train">
    <template v-if="list.length > 0">
      <view class="title">
        <view class="title_content" @click="play()" v-show="type === '1'">
          <text>{{ sentence.chinese }}</text>
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
            mode="widthFix"
          ></image>
        </view>
        <view class="title_content" @click="play()" v-show="type === '2'">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/yinliang.png"
            mode="widthFix"
          ></image>
        </view>
        <view class="selected">
          <view
            class="selected_content"
            v-for="(answer, index) in sentence.answerList"
            :key="index"
            :class="{
              active: answer.word,
              error: sentence.selectList[index].isError,
            }"
          >
            <view
              class="selected_button"
              :class="{
                disabled:
                  sentence.isCorrect === true || sentence.isCorrect === false,
              }"
              @click="checkWord(answer, index)"
            >
              {{ answer.word }}
            </view>
          </view>
        </view>
        <view class="word">
          <view
            class="word_content"
            v-for="(word, index) in sentence.randomWordList"
            :key="index"
            :class="{ select: sentence.selectList[index].selected }"
          >
            <view class="word_button" @click="selectWord(word, index)">
              {{ word }}
            </view>
          </view>
        </view>
        <template v-if="sentence.isCorrect === true">
          <view class="result">
            <view class="result_top">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/correct.png"
              ></image>
              <text class="correct">答对了,正确答案：</text>
            </view>
            <view class="result_bottom">
              {{ sentence.sentence }}
            </view>
          </view>
        </template>
        <template v-if="sentence.isCorrect === false">
          <view class="result">
            <view class="result_top">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/error.png"
              ></image>
              <text class="error">答错了,正确答案：</text>
            </view>
            <view class="result_bottom">
              {{ sentence.sentence }}
            </view>
          </view>
        </template>
      </view>
      <view class="fixed">
        <view class="info">
          <view class="progress">
            <text>{{ currentIndex + 1 }}</text>
            <text>/{{ list.length }}题</text>
          </view>
        </view>
        <view class="button">
          <view
            class="button_content prev"
            :class="{
              disabled: currentIndex === 0,
            }"
            @click="prevQuestion()"
          >
            <text>上一题</text>
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/start_arrow.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="button_content next" @click="nextQuestion()">
            <text>下一题</text>
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/start_arrow.png"
              mode="widthFix"
            ></image>
          </view>
          <view
            class="button_content submit"
            :class="{
              disabled:
                sentence.isCorrect === true || sentence.isCorrect === false,
            }"
            @click="submit()"
          >
            <text>提交</text>
          </view>
          <view
            class="button_content reselection"
            :class="{
              disabled: sentence.isCorrect === true,
            }"
            @click="reselection()"
          >
            <text>重选</text>
          </view>
          <view
            class="button_content remove"
            v-if="sentenceType === 'error' && sentence.isCorrect === true"
            @click="remove()"
          >
            <text>移除错题</text>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <view class="default">
        <span>暂无句子</span>
      </view>
    </template>
    <Tips :show="showTips" :content="tipsContent"></Tips>
  </view>
</template>
<script>
const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
import { editSentenceMemo, deleteSentenceWrong } from "@/api/composition";
export default {
  name: "SentenceTrain",
  props: {
    list: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: "1",
    },
    sentenceType: {
      type: String,
      default: "",
    },
  },
  created() {
    this.init();
  },
  data() {
    return {
      sentence: null,
      currentIndex: 0,
      showTips: false,
      tipsContent: "请提交答案！",
    };
  },
  methods: {
    init() {
      if (this.list.length === 0) return;
      this.initData();
      this.initOptions();
    },
    initData() {
      this.sentence = this.list[this.currentIndex];
      this.$emit("check", this.sentence.id);
    },
    initOptions() {
      let randomWords = this.sentence.randomWords;
      let answerList = [];
      let selectList = [];
      let reg = /\p{P}/u;
      for (let i = 0; i < randomWords.length; i++) {
        if (reg.test(randomWords[i])) {
          answerList.push({ word: randomWords[i], index: i });
          selectList.push({ selected: true });
        } else {
          answerList.push({ word: "", index: -1 });
          selectList.push({ selected: false });
        }
      }
      this.$set(this.sentence, "answerList", answerList);
      this.$set(this.sentence, "selectList", selectList);
      this.$set(this.sentence, "randomWordList", randomWords);
    },
    selectWord(word, i) {
      let isSelected = this.sentence.selectList[i].selected;
      if (isSelected) return;
      let answerList = this.sentence.answerList;
      answerList.some((item, index) => {
        if (item.word === "") {
          answerList.splice(index, 1, { word: word, index: i });
          return true;
        }
      });
      this.sentence.selectList[i].selected = true;
    },
    checkWord(answer, i) {
      if (answer.word === "") return;
      this.sentence.answerList[i].word = "";
      this.sentence.selectList[answer.index].selected = false;
    },
    checkRightAndWrong() {
      let answerList = this.sentence.answerList;
      let sentenceWords = this.sentence.sentenceWords;
      return answerList.some((item, index) => {
        if (item.word !== sentenceWords[index]) {
          return true;
        }
      });
    },
    prevQuestion() {
      this.currentIndex--;
      this.initData();
    },
    nextQuestion() {
      if (this.sentence.isCorrect === undefined) {
        this.showTips = true;
        setTimeout(() => {
          this.showTips = false;
        }, 2000);
        return;
      }
      if (this.currentIndex === this.list.length - 1) {
        this.currentIndex = 0;
        this.$emit("choice");
        return;
      }
      this.currentIndex++;
      this.init();
    },
    submit() {
      if (!this.checkRightAndWrong()) {
        this.$set(this.sentence, "isCorrect", true);
        this.correctNumber += 1;
      } else {
        this.$set(this.sentence, "isCorrect", false);
        this.errorNumber += 1;
        for (let i = 0; i < this.sentence.answerList.length; i++) {
          if (
            this.sentence.answerList[i].word !== this.sentence.sentenceWords[i]
          ) {
            this.$set(this.sentence.selectList[i], "isError", true);
          } else {
            this.$set(this.sentence.selectList[i], "isError", false);
          }
        }
        if (this.sentenceType === "normal") {
          this.saveListeningRec();
        }
      }
    },
    reselection() {
      let isCorrect = this.sentence.isCorrect;
      if (isCorrect !== undefined) {
        this.$set(this.sentence, "isCorrect", undefined);
      }
      this.initOptions();
    },
    remove() {
      uni.showModal({
        title: "提示",
        content: "确定移除该题",
        success: (res) => {
          if (res.confirm) {
            let params = {
              sentenceId: this.sentence.id,
            };
            deleteSentenceWrong(params).then((res) => {
              uni.showModal({
                title: "",
                content: "错题移除成功！",
                showCancel: false,
              });
            });
          }
        },
      });
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.sentence.sentenceAudio;
      englishAudioContext.play();
    },
    saveListeningRec() {
      this.$emit("save", this.sentence.id);
    },
    handleInsertSentence() {
      let params = {
        sentenceId: this.sentence.id,
      };
      editSentenceMemo(params).then((res) => {
        this.value = res.data;
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "./SentenceTrain";
</style>
